#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

// Linux有效， __thread只能修饰内置类型
__thread int gval = 100; // 编译选项，此时每个线程都私有一份。线程的局部存储（线程级别的全局变量）

std::string ToHex(pthread_t tid)
{
    char buffer[128]{};
    snprintf(buffer, sizeof buffer, "0x%lx", tid);

    return buffer;
}

void *threadrun(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        std::cout << name << " is running, tid: " << ToHex(pthread_self()) << " gval: " << gval << std::endl;
        gval++;
        sleep(1);
    }
}

int main()
{
    pthread_t tid; // 线程属性集合的起始虚拟地址--- 在pthread库中维护
    pthread_create(&tid, nullptr, threadrun, (void*)"thread-1");
    while (true)
    {
        std::cout << "main thread, gval: "<< gval << std::endl;
        sleep(1);
    }

    pthread_join(tid, nullptr);

    return 0;
}